<template>
    <div class="info">
        <h3>基本信息</h3>
        <el-row gutter="15">
            <el-col :span="12">
                <el-form-item label="老人姓名" prop="name">
                    <el-input v-model="props.formData.name" type="text" :readonly="type === 'read'" placeholder="请输入老人姓名"
                        clearable :style="{ width: '100%' }" autocomplete="off"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="身份证号" prop="idCardNo">
                    <el-input v-model="props.formData.idCardNo" type="text" :readonly="type === 'read'" placeholder="请输入身份证号"
                        clearable :style="{ width: '100%' }" autocomplete="off"></el-input>
                </el-form-item>
            </el-col>

        </el-row>
        <el-row gutter="15">
            <el-col :span="12">
                <el-form-item label="出生日期" prop="birthday">
                    <el-date-picker v-model="props.formData.birthday" :readonly="type == 'read'" format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD" :style="{ width: '100%' }" placeholder="请选择出生日期"
                        clearable :disabled-date="disabledDate" autocomplete="off"></el-date-picker>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="年龄" prop="age">
                    <el-input v-model="props.formData.age" type="text" :readonly="type == 'read'" placeholder="请输入年龄"
                        clearable :style="{ width: '100%' }" autocomplete="off"></el-input>
                </el-form-item>
            </el-col>

        </el-row>
        <el-row gutter="15">
            <el-col :span="12">
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="props.formData.sex" :readonly="type == 'read'" size="default">
                        <el-radio v-for="(item, index) in sexOptions" :key="index" :label="item.value"
                            :disabled="item.disabled">{{ item.label }}</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="联系方式" prop="phone">
                    <el-input v-model="props.formData.phone" type="text" :readonly="type == 'read'" placeholder="请输入联系方式"
                        clearable :style="{ width: '100%' }" autocomplete="off"></el-input>
                </el-form-item>
            </el-col>

        </el-row>
        <el-row gutter="15">
            <el-col :span="12">
                <el-form-item label="家庭住址" prop="address">
                    <el-input v-model="props.formData.address" type="textarea" :readonly="type == 'read'"
                        placeholder="请输入家庭住址" :autosize="{ minRows: 4, maxRows: 4 }"
                        :style="{ width: '100%' }" autocomplete="off"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="一寸照片" prop="image">
                    <el-image v-if="type === 'read'" style="width: 100px; height: 100px" :src="props.formData.image" />
                    <el-upload v-else ref="image" :file-list="imagefileList" :action="imageAction" :headers="headers"
                        :on-success="(res) => handleSuccess(res, 'image')" :on-remove="() => handleRemove('image')"
                        list-type="picture" :before-upload="imageBeforeUpload" autocomplete="off">
                        <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
                    </el-upload>
                </el-form-item>
            </el-col>

        </el-row>
        <el-row gutter="15">
            <el-col :span="12">
                <el-form-item label="身份证人像面" prop="idCardPortraitImg">
                    <el-image v-if="type === 'read'" style="width: 100px; height: 100px"
                        :src="props.formData.idCardPortraitImg" />
                    <el-upload v-else ref="idCardPortraitImg" :file-list="idCardPortraitImgfileList"
                        :action="idCardPortraitImgAction" :headers="headers"
                        :on-success="(res) => handleSuccess(res, 'idCardPortraitImg')"
                        :on-remove="() => handleRemove('idCardPortraitImg')" list-type="picture"
                        :before-upload="idCardPortraitImgBeforeUpload" autocomplete="off">
                        <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
                    </el-upload>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="身份证国徽面" prop="idCardNationalEmblemImg">
                    <el-image v-if="type === 'read'" style="width: 100px; height: 100px"
                        :src="props.formData.idCardNationalEmblemImg" />
                    <el-upload v-else ref="idCardNationalEmblemImg" :file-list="idCardNationalEmblemImgfileList"
                        :action="idCardNationalEmblemImgAction" :headers="headers"
                        :on-success="(res) => handleSuccess(res, 'idCardNationalEmblemImg')"
                        :on-remove="() => handleRemove('idCardNationalEmblemImg')" list-type="picture"
                        :before-upload="idCardNationalEmblemImgBeforeUpload" autocomplete="off">
                        <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
                    </el-upload>
                </el-form-item>
            </el-col>

        </el-row>
    </div>
</template>
<script setup>
const props = defineProps({
    formData: {
        type: Object,
        required: true
    },
    type: {
        type: String,
        default: () => {
            return {}
        }
    }
})
import {
    ElMessage
} from 'element-plus'
import { getCurrentInstance, watch, ref, reactive, toRefs } from 'vue'
const { proxy } = getCurrentInstance();
const baseUrl = import.meta.env.VITE_APP_BASE_API;

const formRef = ref()
import {
    getToken
} from '@/utils/auth'

const headers = {
    Authorization: 'Bearer ' + getToken()
}
const sexOptions = ref([
    { "label": "男", "value": 1 },
    { "label": "女", "value": 0 }
])

const imageAction = ref('/dev-api/common/upload')
const imagefileList = ref([])
const idCardPortraitImgAction = ref('/dev-api/common/upload')
const idCardPortraitImgfileList = ref([])
const idCardNationalEmblemImgAction = ref('/dev-api/common/upload')
const idCardNationalEmblemImgfileList = ref([])

// 禁用未来日期
const disabledDate = (time) => {
  return time.getTime() > Date.now();
};

// 处理图片路径
function getFullImageUrl(url) {
  if (!url) return '';
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url;
  }
  return baseUrl + url;
}

// 只做图片预览处理，不直接赋值props
const previewFormData = ref({});
watch(() => props.formData, (val) => {
  previewFormData.value = {
    ...val,
    image: getFullImageUrl(val.image),
    idCardPortraitImg: getFullImageUrl(val.idCardPortraitImg),
    idCardNationalEmblemImg: getFullImageUrl(val.idCardNationalEmblemImg)
  };
}, { immediate: true, deep: true })

// 监听出生日期变化，自动计算年龄
const emit = defineEmits(['update:formData'])
watch(() => props.formData.birthday, (newVal) => {
  if (newVal && props.type !== 'read') {
    const birthDate = new Date(newVal);
    const today = new Date();
    let age = today.getFullYear() - birthDate.getFullYear();
    const monthDiff = today.getMonth() - birthDate.getMonth();
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
      age--;
    }
    emit('update:formData', { ...props.formData, age });
  }
});

function imageBeforeUpload(file) {
    let isRightSize = file.size / 1024 / 1024 < 2
    if (!isRightSize) {
        ElMessage.error('文件大小超过 2MB')
    }
    return isRightSize
}
function idCardPortraitImgBeforeUpload(file) {
    let isRightSize = file.size / 1024 / 1024 < 2
    if (!isRightSize) {
        ElMessage.error('文件大小超过 2MB')
    }
    return isRightSize
}
function idCardNationalEmblemImgBeforeUpload(file) {
    let isRightSize = file.size / 1024 / 1024 < 2
    if (!isRightSize) {
        ElMessage.error('文件大小超过 2MB')
    }
    return isRightSize
}

//上传文件成功
const handleSuccess = (res, key) => {
    emit('update:formData', { ...props.formData, [key]: res.url });
}
//移除文件
const handleRemove = (key) => {
    emit('update:formData', { ...props.formData, [key]: '' });
}

//监听数据，如果发生变化，则发送数据给父组件
// watch(() => props.formData, (val) => {
//     emit('getFormData', val)
// }, { immediate: true, deep: true })

defineExpose({
    // rules 由父表单统一管理
})
</script>
<style>
.el-upload__tip {
    line-height: 1.2;
}
</style>
<style src="../index.scss"></style>